﻿using System;
using System.Linq;
using System.Windows.Forms;
using Tiwo.Design.Renderers;

namespace Tiwo.Design
{
    public partial class TiwoSchemeEditor : UserControl
    {
        public TiwoSchemeEditor()
        {
            InitializeComponent();

            Environment = new Environment();
            EnvironmentListener = new EnvironmentListener(this, Environment);

            SchemeWrapper = new SchemeEditable(pnSite, Environment);
        }

        public Environment Environment { get; private set; }

        private EnvironmentListener EnvironmentListener { get; set; }
        private SchemeEditable SchemeWrapper { get; set; }

        public void LoadScheme(Scheme scheme)
        {
            SchemeWrapper.Scheme = new SchemeMerger(new Scheme()).CopyFrom(scheme);
        }

        public void SaveScheme(Scheme scheme)
        {
            new SchemeMerger(scheme).CopyFrom(SchemeWrapper.Scheme);
        }

        private void pnSite_ItemHover(object sender, RendererEventArgs e)
        {
            if (e.Renderer is IDescriptor)
            {
                tsItemName.Text = ((IDescriptor)e.Renderer).FriendlyName;
            }
        }

        private void pnSite_ItemLeave(object sender, RendererEventArgs e)
        {
            tsItemName.Text = string.Empty;
        }

        private void menuAddInput_Click(object sender, EventArgs e)
        {
            SchemeWrapper.CreateNewInput();
        }

        private void pnSite_ShowContextMenu(object sender, EventArgs e)
        {
            contextMenu.Show(pnSite, pnSite.PointToClient(MousePosition));
        }

        private void pnSite_ShowActionMenu(object sender, ActionListEventArgs e)
        {
            contextActionMenu.Items.Clear();
            contextActionMenu.Items.AddRange(e.ActionList.Select(a => CreateActionMenu(a)).ToArray());
            contextActionMenu.Show(pnSite, pnSite.PointToClient(MousePosition));
        }

        private ToolStripMenuItem CreateActionMenu(ActionVerb action)
        {
            var menuItem = new ToolStripMenuItem
            {
                Text = action.Title
            };

            menuItem.Click += (_1, _2) =>
            {
                action.Run();
                pnSite.Invalidate();
            };

            return menuItem;
        }
    }
}
